/*
 * Copyright 2013 Sigurd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.client.infrastructure.rest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import de.digiway.rapidbreeze.client.model.config.ServerConfigurationResourceRepository;
import de.digiway.rapidbreeze.shared.rest.ResourceLocation;
import de.digiway.rapidbreeze.shared.rest.config.ServerConfigurationResourceEntry;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

/**
 *
 * @author Sigurd
 */
public class ServerConfigurationResourceRestClient implements ServerConfigurationResourceRepository {

    private Client client;
    private String host;
    private String username;
    private String password;
    private int port;

    public ServerConfigurationResourceRestClient(String host, int port, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
        this.client = Client.create();
    }

    @Override
    public void setConfiguration(String key, Object value) {
        Validate.notEmpty(key, "A key must be provided.");
        ServerConfigurationResourceEntry resource = new ServerConfigurationResourceEntry(key, value);

        try {
            URI uri = getUri(ResourceLocation.SERVER_CONFIGURATION_RESOURCE_PATH);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).put(ClientResponse.class, resource);
            if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) {
                throw new IllegalStateException("An error in the restful resource repository occured:" + response.getEntity(String.class) + ". Cannot update resource:" + resource);
            }
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }

    @Override
    public boolean hasConfiguration(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        
        try {
            URI uri = getUri(ResourceLocation.SERVER_CONFIGURATION_RESOURCE_PATH, key);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            return response.getStatus() == ClientResponse.Status.OK.getStatusCode();
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }

    @Override
    public <T> T getConfiguration(String key) {
        Validate.notEmpty(key, "A key must be provided.");
        try {
            URI uri = getUri(ResourceLocation.SERVER_CONFIGURATION_RESOURCE_PATH, key);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) {
                throw new IllegalStateException("An error in the restful resource repository occured:" + response.getEntity(String.class) + ". Cannot get configuration resource for key:" + key);
            }
            return response.getEntity(ServerConfigurationResourceEntry.class).getValue();
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }

    private URI getUri(String... paths) throws URISyntaxException {
        UriBuilder builder = UriBuilder.fromPath("http://" + host + ":" + port);
        for (String path : paths) {
            builder.path(path);
        }
        return builder.build();
    }

    @Override
    public List<ServerConfigurationResourceEntry> getEntries() {
        try {
            URI uri = getUri(ResourceLocation.SERVER_CONFIGURATION_RESOURCE_PATH);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) {
                throw new IllegalStateException("An error in the restful resource repository occured:" + response.getEntity(String.class) + ". Cannot get all configurations.");
            }
            GenericType<List<ServerConfigurationResourceEntry>> type = new GenericType<List<ServerConfigurationResourceEntry>>() {
            };
            return response.getEntity(type);
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }
}
